# -*- coding: utf-8 -*-
from threading import Thread, Event
from config import TIME_SLOG, DATA_FILE_PATH, INDEX_FILE, IMAGE_FILE, CATEGORY, CUSTOM_DATA_FILE_PATH
import xlrd
import requests
from utils.TaoKeyUtil import get_tao_key
from weibo.WBPoster import WeiboSender
from weibo.WBGroup import WeiboGroup
from weibo.WBComment import WeiboComment
import subprocess
import time


class BaicaiPoster(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.stopped = Event()
        self.count = 0
        self.send_list = []
        self.last_time = time.time()

    def run(self):
        self.task_funtion()
        while not self.stopped.wait(TIME_SLOG):
            self.task_funtion()

    def stop(self):
        self.stopped.set()

    def task_funtion(self):

        if time.time() - self.last_time > 24 * 3600:
            self.count = 0
            self.send_list = []
            self.last_time = time.time()

        content, img = self.get_weibo_content_from_api()

        headers = {"Accept": "text/html,application/xhtml+xml,application/xml;",
                   "Accept-Encoding": "gzip",
                   "Accept-Language": "zh-CN,zh;q=0.8",
                   "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
                   }
        response = requests.get(img, headers=headers)
        with open(IMAGE_FILE, 'wb') as f:
            f.write(response.content)
        f.close()

        weibosender = WeiboSender()
        group = WeiboGroup()
        url, mid = weibosender.send_weibo(content, IMAGE_FILE)
        if url is not None:
            groups = group.get_all_groups()
            for g in groups:
                group.send_to_group(g, url)

    def get_weibo_content_from_api(self):
        python3_command = 'python2 utils/TaobaoCoupon.py ' + str(self.count)  # launch your python2 script using bash
        process = subprocess.run(python3_command.split(), stdout=subprocess.PIPE)
        while process.stdout.decode('utf-8').strip() == '' or process.stdout.decode('utf-8').strip().split('|')[
            2] in self.send_list:
            self.count = self.count + 1
            python3_command = 'python2 utils/TaobaoCoupon.py ' + str(self.count)  #
            process = subprocess.run(python3_command.split(), stdout=subprocess.PIPE)
            print(str(self.count))
        print(process.stdout.decode('utf-8').strip())
        contents = process.stdout.decode('utf-8').strip().split('|')
        self.count = self.count + 1
        self.send_list.append(contents[2])
        return contents[0], contents[1]

    def get_weibo_content(self):
        data = xlrd.open_workbook(DATA_FILE_PATH)
        table = data.sheets()[0]
        with open(INDEX_FILE, 'r') as f:
            start = int(f.read())
        for index in range(start, table.nrows):
            name = table.cell(index, 1).value
            img = table.cell(index, 2).value
            category = table.cell(index, 4).value
            nunmber = int(table.cell(index, 7).value)
            payback = float(table.cell(index, 8).value)
            platform = table.cell(index, 13).value
            try:
                a = category[:category.index('/')]
            except ValueError:
                a = category
            if platform == '天猫' and a in CATEGORY and nunmber > 500 and payback > 30:
                price = table.cell(index, 6).value
                card = table.cell(index, 17).value
                discount = table.cell(index, 21).value
                try:
                    after = round(float(price) - float(card[:card.index(u'元无条件券')]), 2)
                except ValueError:
                    after = round(float(price) - float(card[card.index(u'减') + 1:len(card) - 1]), 2)
                content = u'#每日白菜价精选#' + name + u'\n券后价：' + str(after) + u'\n淘口令：' + get_tao_key(name, discount,
                                                                                                 img) + u'\n优惠券购买：' + discount
                with open(INDEX_FILE, 'w') as file:
                    file.write(str(index + 1))
                return content, img

    def get_custom_data(self):
        data = xlrd.open_workbook(CUSTOM_DATA_FILE_PATH)
        table = data.sheets()[0]
        with open(INDEX_FILE, 'r') as f:
            start = int(f.read())
        for index in range(start, table.nrows):
            name = table.cell(index, 1).value
            img = table.cell(index, 2).value

            price = table.cell(index, 5).value
            card = table.cell(index, 20).value
            discount = table.cell(index, 25).value
            key = table.cell(index, 24).value
            try:
                after = round(float(price) - float(card[:card.index(u'元无条件券')]), 2)
            except ValueError:
                after = round(float(price) - float(card[card.index(u'减') + 1:len(card) - 1]), 2)
            content = u'#每日白菜价精选#' + name + u'\n券后价：' + str(after) + u'\n淘口令：' + key + u'\n优惠券购买：' + discount
            with open(INDEX_FILE, 'w') as file:
                file.write(str(index + 1))
                return content, img
